<template>
  <div class="all">
    <div class="title">
      <div>{{ title }}</div>
      <div>
        <el-button v-if="data.status === 30 && roles.includes('WorkOrderPmEngineer')" type="success" icon="el-icon-circle-check" @click="engineerReview(1)">工程师审核</el-button>
        <el-button v-if="data.status === 30 && roles.includes('WorkOrderPmEngineer')" type="danger" icon="el-icon-circle-close" @click="engineerReview(2)">驳回</el-button>
        <el-button v-if="data.status === 20 && roles.includes('WorkOrderPmMonitor')" type="danger" icon="el-icon-circle-close" @click="monitorReview(2)">驳回</el-button>
        <el-button v-if="data.status === 20 && roles.includes('WorkOrderPmMonitor')" type="success" icon="el-icon-circle-check" @click="monitorReview(1)">班长审核</el-button>
        <el-button v-if="data.status === 10" type="success" icon="el-icon-circle-check" @click="handOut">派发</el-button>
        <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
        <el-button style="display: none" v-if="roles.includes('WorkOrderPm1Delete')" type="danger" icon="el-icon-delete" @click="delBtn">删除</el-button>
      </div>
    </div>
    <div class="detail-mid">
      <el-form ref="form" v-loading="loading" :model="data" inline>
        <el-row>
          <el-col :span="4">
            <el-form-item label="编号：" prop="coding">
              <el-input v-model="data.coding" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="工单类型：">
              <el-input v-model="data.category" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="负责人：">
              <el-input v-model="data.admin" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="安排时间：" prop="arrange_time">
              <el-input v-model="data.arrange_time" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="截止时间：" prop="end_time">
              <el-input v-model="data.end_time" readonly />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="完成时间：">
              <el-input v-model="data.complete_time" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="是否停机：" prop="halt">
              <SelfSelect v-model="data.halt" :show-list="YN" disabled :clearable="false" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="设备：" prop="equipment_id">
              <el-input v-model="data.equipment" readonly />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="车间：">
              <el-input v-model="data.workshop" readonly />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="生产线：">
              <el-input v-model="data.line" readonly />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="工位：">
              <el-input v-model="data.process" readonly />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="周期：">
              <el-input v-model="data.period" readonly />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="周期单位：">
              <SelfSelect v-model="data.period_unit" :show-list="planUnit" disabled :clearable="false" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="任务时长（小时）：" prop="task_long">
              <el-input v-model="data.task_long" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="状态：">
              <SelfSelect v-model="data.status" :show-list="pmStatus" disabled :clearable="false" />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="扫描二维码时间：">
              <el-input v-model="data.qrcode_time" clearable readonly />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="提交时间：">
              <el-input v-model="data.submit_complete" clearable readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="期望工时（分钟）：" prop="expect_man_minutes">
              <el-input v-model="data.expect_man_minutes" clearable readonly />
            </el-form-item>
          </el-col>
          <el-col v-if="editId" :span="4">
            <el-form-item label="实际工时（分钟）：">
              <el-input v-model="data.actual_man_minutes" clearable readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="专业：" prop="profession">
              <SelfSelect v-model="data.profession" :show-list="pmProfession" disabled :clearable="false" />
            </el-form-item>
          </el-col>
          <el-col v-if="editId && data.status1 > 0" :span="4">
            <el-form-item label="超时前状态：">
              <SelfSelect v-model="data.status1" :show-list="pmStatus" disabled />
            </el-form-item>
          </el-col>
          <el-col v-if="false" :span="4">
            <el-form-item label="延期时长（小时）：">
              <el-input v-model="data.delay" clearable readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="detail-bottom">
      <el-tabs>
        <el-tab-pane v-if="roles.includes('WorkOrderPm1Update')" label="任务">
          <div class="detail-table">
            <el-table ref="multipleTable" tooltip-effect="dark" width="100%" :data="data.other_task">
              <el-table-column prop="part" label="部位" align="left" min-width="12%" />
              <el-table-column prop="param" label="项目内容" align="left" min-width="12%" />
              <el-table-column prop="param_detail" label="判定标准" align="left" min-width="14%" />
              <el-table-column prop="task" label="方法" align="left" min-width="10%" />
              <el-table-column prop="max" label="最大值" align="left" min-width="10%" />
              <el-table-column prop="min" label="最小值" align="left" min-width="10%" />
              <el-table-column prop="reading" label="读数" min-width="14%" align="left">
                <template scope="scope">
                  <div v-if="scope.row.type === 1">
                    <el-radio-group v-model="scope.row.reading">
                      <el-radio label="1">正常</el-radio>
                      <el-radio label="2">不正常</el-radio>
                    </el-radio-group>
                  </div>
                  <div v-if="scope.row.type === 2">
                    <el-input v-model="scope.row.reading" clearable style="width: 60%" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="admin" label="执行人" align="left" min-width="10%" />
              <el-table-column label="照片" min-width="10%">
                <template scope="scope">
                  <el-image v-if="scope.row.photo" style="width: 100px; height: 100px" :src="scope.row.photo" :preview-src-list="[scope.row.photo]">
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="left" width="5%">
                <template scope="scope">
                  <div v-if="data.status === 1">
                    <el-button class="delBtn" type="text" size="small" @click="taskDel(scope.row.id)">删除</el-button>
                  </div>
                  <div v-else>
                    <span>-</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-form ref="taskFrom" :model="data" inline>
            <el-row style="margin-top: 20px" :gutter="15">
              <el-button style="margin-left: 10px;" type="primary" icon="el-icon-document" @click="submitReading">提交</el-button>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane v-if="roles.includes('WorkOrderPm1Update')" label="执行人">
          <div class="detail-table">
            <el-table ref="multipleTable" tooltip-effect="dark" width="100%" :data="data.other_member">
              <el-table-column prop="admin" label="人员" align="left" min-width="29%" />
              <el-table-column label="操作" align="left" min-width="70%">
                <template scope="scope">
                  <div v-if="canConfirm">
                    <el-button class="delBtn" type="text" size="small" @click="memberDel(scope.row.id)">删除</el-button>
                  </div>
                  <div v-else>
                    <span>-</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-form v-if="canConfirm" ref="adminFrom" :model="data" inline>
            <el-row style="margin-top: 20px" class="input clearables" :gutter="15">
              <el-col :span="7">
                <el-form-item>
                  <Selects v-model="admin_id" action="adminList" />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-button icon="el-icon-upload2" @click="memberSubmit(2)" />
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane v-if="roles.includes('WorkOrderPm1Update')" label="时间">
          <div class="detail-table">
            <el-table ref="multipleTable" tooltip-effect="dark" width="100%" :data="data.other_time">
              <el-table-column prop="start_time" label="开始时间" align="left" min-width="38%" />
              <el-table-column prop="end_time" label="结束时间" align="left" min-width="40%" />
              <el-table-column label="操作" align="left" min-width="20%">
                <template scope="scope">
                  <div v-if="canConfirm">
                    <el-button class="delBtn" type="text" size="small" @click="timeDel(scope.row.id)">删除</el-button>
                  </div>
                  <div v-else>
                    <span>-</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-form v-if="canConfirm" ref="adminFrom" :model="data" inline>
            <el-row style="margin-top: 20px" class="input clearables" :gutter="15">
              <el-col :span="9">
                <el-form-item>
                  <el-date-picker v-model="start_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item>
                  <el-date-picker v-model="end_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-button icon="el-icon-upload2" @click="timeSubmit" />
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="描述">
          <el-row v-if="editId" :gutter="20" style="padding: 2px">
            <el-col :span="4">
              <div>
                <p>创建时间日期</p>
                <el-input v-model="data.create_time" clearable readonly />
              </div>
              <div>
                <p>创建人</p>
                <el-input v-model="data.create_admin" clearable readonly />
              </div>
              <div v-if="data.update_time">
                <p>最近更新</p>
                <el-input v-model="data.update_time" clearable readonly />
                <p>更新者</p>
                <el-input v-model="data.update_admin" clearable readonly />
              </div>
            </el-col>
            <el-col :span="16">
              <TinyMce v-model="data.content" />
            </el-col>
            <el-col class="upload" :span="4">
              <Adjunct :pk="editId" table="pm1" />
            </el-col>
          </el-row>
          <el-row v-if="!editId" :gutter="20" style="padding: 2px">
            <el-col :span="24">
              <TinyMce v-model="data.content" />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import API from '@/api/workorder/pm'
import SelfSelect from '@/components/select-o'
import TinyMce from '@/components/Tinymce/index'
import Selects from '@/components/select-search'
import Adjunct from '@/components/Upload/adjunct'
import { YN, pmProfession, pmType, pmStatus, isEngineer, planUnit } from '@/utils/option'
import XLSX from 'xlsx'
import { mapGetters } from 'vuex'
export default {
  inject: ['goUrl', 'isEdit', 'add', 'update', 'reload'],
  components: {
    SelfSelect,
    TinyMce,
    Selects,
    Adjunct
  },
  data() {
    return {
      data: {
        status: 1,
        plan_category: 1
      },
      task: {
        admin_id: null
      },
      editId: null,
      title: '',
      YN,
      pmStatus,
      partsIndex: null,
      parts_id: null,
      number: null,
      remark: null,
      part: null,
      param: null,
      param_detail: null,
      task_id: null,
      task_unit: null,
      max: null,
      min: null,
      reading: null,
      admin_id: null,
      engineer: null,
      editNumber: null,
      editRemark: null,
      editPartsId: null,
      start_time: null,
      end_time: null,
      pmProfession,
      pmType,
      planUnit,
      isEngineer,
      status: 0,
      canConfirm: false,
      loading: true
    }
  },
  created() {
    const edit = this.isEdit()
    if (edit) {
      this.title = '自主点检详情'
      this.editId = edit
      this.info()
    } else {
      this.loading = false
      this.title = '新增自主点检'
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  methods: {
    goBack() {
      this.$router.push('/workOrder/pm1')
    },
    info() {
      API.getOne(this.editId).then(res => {
        this.data = res.data
        this.grant()
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
    delBtn() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = this.editId
        API.delete(id).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.$message.success('删除成功')
            this.goBack()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitReading() {
      const other_task = Object.assign({}, this.data.other_task)
      const data = {
        data: other_task,
        id: this.editId
      }
      API.submit(data).then(res => {
        if (res.data.error_code === 1) {
          this.$message.success('提交完成')
          this.$router.push('/workOrder/pm1')
        } else if (res.data.error_code === 11) {
          this.$message.success('完成并生成保修单')
          this.$router.push('/workOrder/pm1')
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    monitorReview(status) {
      const monitorData = {
        id: this.editId,
        status: status
      }
      API.monitorReview(monitorData).then(res => {
        if (res.data.error_code === 1) {
          this.$message({
            message: '审核成功',
            type: 'success'
          })
        } else {
          this.$message.error('审核失败')
        }
      })
    },
    engineerReview(status) {
      const engineerData = {
        id: this.editId,
        status: status
      }
      API.engineerReview(engineerData).then(res => {
        if (res.data.error_code === 1) {
          this.$message({
            message: '审核成功',
            type: 'success'
          })
        } else {
          this.$message.error('审核失败')
        }
      })
    },
    editPartsTable({ $index, row }) {
      // 获取当前点击行下标
      this.partsIndex = $index
      this.editPartsId = row.parts_id
      this.editNumber = row.number
      this.editRemark = row.remark
    },
    savePartsTable({ row }) {
      this.partsIndex = null
      const partsData = {
        id: row.id,
        number: this.editNumber
        // price: parseInt(this.editPrice)
      }
      API.editParts(partsData).then(res => {
        if (res.data.error_code !== 1) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('更新成功')
        }
      }).finally(() => {
        this.info()
      })
    },
    taskDel(id) {
      API.removeTask(id).then(res => {
        if (res.data.error_code !== 1) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('删除成功')
        }
      }).finally(() => {
        this.info()
      })
    },
    taskSubmit() {
      const partsData = {
        part: this.part,
        workorder_id: this.editId,
        param: this.param,
        task_unit: this.task_unit,
        param_detail: this.param_detail,
        task_id: this.task_id,
        reading: this.reading,
        max: this.max,
        min: this.min,
        admin_id: this.task.admin_id
      }
      API.appendTask(partsData).then(res => {
        if (res.data.error_code === 1) {
          this.$message.success('新增成功')
          this.info()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    partsSubmit() {
      const partsData = {
        workorder_id: this.editId,
        parts_id: this.parts_id,
        number: this.number,
        remark: this.remark
      }
      API.appendParts(partsData).then(res => {
        if (res.data.error_code === 1) {
          this.$message.success('新增成功')
          this.info()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    submitForm() {
      if (this.editId) {
        this.update(API, this.data, this.$refs['form'], '/workOrder/pm1')
      } else {
        this.add(API, this.data, this.$refs['form'], '/workOrder/pm1/edit/')
      }
    },
    memberDel(id) {
      API.removeMember(id).then(res => {
        if (res.data.error_code !== 1) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('删除成功')
        }
      }).finally(() => {
        this.info()
      })
    },
    partsDel(id) {
      API.removeParts(id).then(res => {
        if (res.data.error_code !== 1) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('删除成功')
        }
      }).finally(() => {
        this.info()
      })
    },
    memberSubmit(engineer) {
      const partsData = {
        engineer: engineer,
        workorder_id: this.editId,
        admin_id: this.admin_id
      }
      API.appendMember(partsData).then(res => {
        if (res.data.error_code === 1) {
          this.$message.success('新增成功')
          this.info()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    timeSubmit() {
      const timeData = {
        end_time: this.end_time,
        start_time: this.start_time,
        workorder_id: this.editId
      }
      API.appendTime(timeData).then(res => {
        if (res.data.error_code === 1) {
          this.$message.success('新增成功')
          this.info()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    timeDel(id) {
      API.removeTime(id).then(res => {
        if (res.data.error_code !== 1) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('删除成功')
        }
      }).finally(() => {
        this.info()
      })
    },
    // requestParts() {
    //   API.requestParts({ id: this.editId }).then(res => {
    //     if (res.data.error_code === 1) {
    //       this.$message.success('请求成功，请去库房领取')
    //       this.info()
    //     } else {
    //       this.$message.error(res.data.message)
    //     }
    //   })
    // },
    handOut() {
      const newData = {
        id: this.editId,
        arrange_time: this.data.arrange_time,
        end_time: this.data.end_time
      }
      API.handOut(newData).then(res => {
        if (res.data.error_code === 1) {
          this.$message.success('派发成功')
          this.info()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    workbook(file) {
      const reader = new FileReader()
      const self = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        const postData = {}
        postData.outData = outData
        API.excel(postData).then(response => {
          if (response.data.error_code === 1) {
            self.$message.success(`恭喜你，操作成功`)
            self.reload()
          } else {
            self.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    grant() {
      if ([1, 100].includes(this.data.status)) {
        this.canConfirm = true
      }
    }
  }
}
</script>

<style scoped>
  .takeImport{
    margin-right: 10px;
  }
  .takeImport .el-button--primary{
    height: 30px;
  }
</style>
